<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace common\behavior;


use common\model\TaskRelationModel;
use support\Db;

/**
 * 行为扩展：创建task_relation_分表
 */
class TaskRelationProjectTableCreatedEventBehavior
{

    /**
     * 创建 task_relation 分表
     * @param $params
     * @return void
     * @throws \Exception
     */
    public function run(&$params)
    {
        if (empty($params['data']['id'])) {
            return;
        }
        $projectId = $params['data']['id'];
        $taskRelationTableName = model(TaskRelationModel::class)->getTableName(); // 维护一张基础表
        $createdPartitionTableList = model(TaskRelationModel::class)->query('SHOW CREATE TABLE ' . $taskRelationTableName);
        if (empty($createdPartitionTableList[0]['create table'])) {
            return;
        }
        $createdPartitionTableListSql = $createdPartitionTableList[0]['create table'];
        $newTableName = sprintf('task_relation_project_%d', $projectId);
        // 判断表是否存在
        $tableIsExists = Db::query('SHOW TABLES LIKE ' . "'$newTableName'");
        if (!empty($tableIsExists)) {
            return;
        }
        $tmpCreatedPartitionTableListSql = str_replace('task_relation', $newTableName, $createdPartitionTableListSql);
        db::execute($tmpCreatedPartitionTableListSql);
    }

}
